package com.enjoychain.www.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoychain.www.patrol.service.IEcJobService;
import com.enjoychain.www.patrol.service.IEcTaskService;
import com.enjoychain.www.security.constant.BusinessTaskType;
import com.enjoychain.www.common.constrants.TaskStatus;
import com.enjoychain.www.security.entity.*;
import com.enjoychain.www.security.entity.task.TaskInfo;
import com.enjoychain.www.security.mapper.TaskInfoMapper;
import com.enjoychain.www.security.pojo.TaskPojo;
import com.enjoychain.www.security.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 任务基础信息表 服务实现类
 * </p>
 *
 * @author ddmonk
 * @since 2023-01-20
 */
@Service
@Slf4j
public class TaskInfoServiceImpl extends ServiceImpl<TaskInfoMapper, TaskInfo> implements ITaskInfoService {

    @Autowired
    ITaskDetailItemService itemService;

    @Autowired
    IJobInfoService jobInfoService;

    @Autowired
    ICorpBasicInfoService basicInfoService;

    @Autowired
    IXcBasicService basicService;

    @Autowired
    ITaskCorpEnvBasicInfoService taskCorpEnvBasicInfoService;

    @Autowired
    ICorpEnvBasicInfoService envBasicInfoService;

    @Autowired
    IBasicFileService fileService;

    @Autowired
    ITaskEnvService taskEnvService;

    @Autowired
    ITaskSecService taskSecService;

    @Autowired
    ICorpSecCorpBasicService secCorpBasicService;

    @Autowired
    IEcJobService ecJobService;

    @Autowired
    IEcTaskService ecTaskService;

    @Override
    public TaskInfo getTaskDetailById(String id) {
        TaskInfo info = getById(id);
        info.setItemList(itemService.getItems(id));
        return info;
    }

    @Override
    public boolean removeBatchByIdsWithItems(List<String> asList) {
        this.removeBatchByIds(asList);
        itemService.removeBatchByTaskIds(asList);
        //todo 删除图片

        for (String taskId : asList){
            removeByTaskId(taskId);
        }
        return true;
    }

    @Override
    public IPage<TaskInfo> getPageByAccId(Page<TaskInfo> page, String accId) {
        return baseMapper.pageByAccId(page,accId);
    }

    private boolean hasRunningTask(String corpId, BusinessTaskType type){
        QueryWrapper<TaskInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("corp_id",corpId);
        queryWrapper.eq("type", type.getValue());
        queryWrapper.in("status",TaskStatus.PLAN,TaskStatus.DOING);
        return list(queryWrapper).size() > 0;
    }


    @Override
    public boolean buildTask(String jobId, String corpId) {
        return jobInfoService.buildSingleTask(basicInfoService.getById(corpId), jobInfoService.getJobDetail(jobId));
    }

    @Override
    @Transactional
    public TaskPojo buildNewTask(String certNo, BusinessTaskType type, String taskType) {
        //1、判断当前该企业是否有正在运行的任务，如果有，不允许创建。
        String taskId = UUID.randomUUID().toString().replace("-","");
        TaskPojo taskPojo = new TaskPojo();
        taskPojo.setId(taskId);

        CorpBasicInfo temp = basicInfoService.buildBasicInfoByCertNo(certNo);

        //todo 如果两个业务都涉及

        //1、如果企业列表中没有，需要新增
        CorpBasicInfo basicInfo = basicInfoService.rebuild(temp);
        if (StringUtils.isEmpty(basicInfo.getBusiType() ) || !basicInfo.getBusiType().contains(type.getValue())){
            if (StringUtils.isEmpty(basicInfo.getBusiType())){
                basicInfo.setBusiType(type.getValue());
            }else {
                basicInfo.setBusiType(basicInfo.getBusiType() + "," + type.getValue());
            }
        }
        basicInfoService.saveOrUpdate(basicInfo);
        if (hasRunningTask(basicInfo.getId(),type)){
            throw new ServiceException("当前企业有正在执行或计划中的任务");
        }
        //2、构建任务
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setTaskNo(basicService.getTaskNo());
        taskInfo.setId(taskId);
        taskInfo.setCorpId(basicInfo.getId());
        taskInfo.setCorpName(basicInfo.getName());
        taskInfo.setStatus(TaskStatus.PLAN);
        taskInfo.setType(type.getValue());
        taskInfo.setNum((getTaskNumByCorpIdForYear(basicInfo.getId())+1) + "");
        if (BusinessTaskType.ENVIRONMENT == type) {
            taskInfo.setName(DateUtils.dateTime() + "-" + basicInfo.getName() + "—环保巡查任务");
        }else if (BusinessTaskType.SECURITY == type){
            taskInfo.setName(DateUtils.dateTime() + "-" + basicInfo.getName() + "—安全巡查任务");
        }else {
            String jobType = ecJobService.getJobNameByBussinessId(taskType);
            taskInfo.setName(DateUtils.dateTime() + "-" + basicInfo.getName() + "—" +jobType);
        }
        this.save(taskInfo);
        if (BusinessTaskType.ENVIRONMENT == type){
            taskEnvService.buildEnvTask(basicInfo, taskId);
        }else if (BusinessTaskType.SECURITY == type){
            taskSecService.buildSecTask(basicInfo, taskId);
        }else {
            ecJobService.buildTaskBy(certNo,taskType, taskId);
        }
        return getTaskPojo(taskId);
    }

    @Override
    @Transactional
    public TaskPojo update(TaskPojo taskPojo, boolean isCorrect) {
        // 1、更改状态
        TaskInfo old = getById(taskPojo.getId());
        // 计划中 -> 正在进行
        if (old.getStatus()==TaskStatus.PLAN && taskPojo.getTaskInfo().getStatus() == TaskStatus.DOING){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            taskPojo.getTaskInfo().setHandlerId(user.getUserId()+"");
            taskPojo.getTaskInfo().setHandlerName(user.getNickName());
            taskPojo.getTaskInfo().setStartTime(LocalDateTime.now());
        }
        // 正在进行
        if ((taskPojo.getTaskInfo().getStatus() == TaskStatus.FINISH || taskPojo.getTaskInfo().getStatus() == TaskStatus.STOP) && !isCorrect){
            taskPojo.getTaskInfo().setEndTime(LocalDateTime.now());
            CorpBasicInfo corpBasicInfo = null;
            // 要把当前的基础信息内容覆盖原有基础数据。
            if (taskPojo.getTaskInfo().getType().equals(BusinessTaskType.ENVIRONMENT.getValue())) {
                corpBasicInfo = basicInfoService.getById(taskPojo.getEnvCorpInfo().getCorpId());
                corpBasicInfo.setLinkName(taskPojo.getEnvCorpInfo().getLinkName());
                corpBasicInfo.setLinkTel(taskPojo.getEnvCorpInfo().getLinkTel());
                corpBasicInfo.setAdminArea(taskPojo.getEnvCorpInfo().getAdminArea());
                corpBasicInfo.setLastServiceTime(LocalDateTime.now());
                envBasicInfoService.saveOrUpdateDetail(taskPojo.getEnvCorpInfo());
            }else if (taskPojo.getTaskInfo().getType().equals(BusinessTaskType.SECURITY.getValue())){
                secCorpBasicService.saveOrUpdateDetail(taskPojo.getSecBasicInfo());
                corpBasicInfo = basicInfoService.getById(taskPojo.getSecBasicInfo().getCorpId());
                corpBasicInfo.setLastServiceTime(LocalDateTime.now());
            }
            if (null != corpBasicInfo ) {
                basicInfoService.saveOrUpdate(corpBasicInfo);
            }
        }

        this.updateById(taskPojo.getTaskInfo());
        if (taskPojo.getTaskInfo().getType().equals(BusinessTaskType.ENVIRONMENT.getValue())) {
            //1、更新基础信息
            taskEnvService.saveEnvCorpBasicInfo(taskPojo);
            //2、基于基础信息更新巡查细项。
            taskEnvService.saveEnvTaskDetail(taskPojo);
        }else if (taskPojo.getTaskInfo().getType().equals(BusinessTaskType.SECURITY.getValue())){
            taskSecService.saveSecCorpBasicInfo(taskPojo);
            taskSecService.saveSecTaskDetail(taskPojo);
        } else {
            ecTaskService.updateTask(taskPojo.getCommonTask());
        }
        return getTaskPojo(taskPojo.getId());
    }


    @Override
    public TaskPojo getTaskPojo(String taskId) {
        TaskPojo pojo = new TaskPojo();
        log.info("================" + taskId + "==================");
        TaskInfo info = getById(taskId);
        pojo.setTaskInfo(info);
        pojo.setId(taskId);
        if (info.getType().equals(BusinessTaskType.ENVIRONMENT.getValue())) {
            pojo.setEnvCorpInfo(taskEnvService.getCorpEnvBasicInfoByTaskId(taskId));
            pojo.setEnvTaskDetail(taskEnvService.getEnvTaskDetailByTaskId(taskId));
        }else if (info.getType().equals(BusinessTaskType.SECURITY.getValue())){
            pojo.setSecBasicInfo(taskSecService.getCorpSecBasicInfoByTaskId(taskId));
            pojo.setSecTaskDetail(taskSecService.getSecTaskDetailByTaskId(taskId));
        } else {
            pojo.setCommonTask(ecTaskService.getDetailById(taskId));
        }
        return pojo;
    }

    @Override
    public void removeByTaskId(String taskId) {
        removeById(taskId);
        taskEnvService.removeByTaskId(taskId);
        taskSecService.removeByTaskId(taskId);
    }

//    @Override
//    public TaskInfo getRecentlyFinishTaskByCertNo(String certNo) {
//        return this.baseMapper.getRecentlyFinishTaskByCertNo(certNo);
//    }

    int getTaskNumByCorpIdForYear(String corpId){
        return baseMapper.countFinishTaskByCorpId(corpId);
    }

}
